<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\AclUser;
use ffhome\common\util\CommonUtil;
use ffhome\util\JwtAuth;
use think\captcha\facade\Captcha;
use think\facade\Cache;

class Login extends CommonController
{
    /**
     * 初始化方法
     */
    public function initialize()
    {
        parent::initialize();
        $action = $this->request->action();
        $id = currentUserId();
        if (!empty($id) && !in_array($action, ['out'])) {
            $moduleName = app('http')->getName();
            $this->success(lang('login.already_login'), [], __url("@{$moduleName}"));
        }
    }

    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $captcha = config('app.captcha');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'username|' . lang('login.username') => 'require',
                'password|' . lang('login.password') => 'require',
                'keep_login|' . lang('login.keep') => 'require',
            ];
            $captcha == 1 && $rule['captcha|' . lang('login.captcha')] = 'require|captcha';
            $this->validate($post, $rule);
            $user = authService()->getUserByUserName($post['username']);
            if (empty($user)) {
                $this->error(lang('login.user_not_exist'));
            }
            if (CommonUtil::password($post['password']) != $user['password']) {
                $this->error(lang('login.password_error'));
            }
            AclUser::updateLogin($user['id']);
            cookie('username', $post['username'], 86400 * 365);
            if ($post['keep_login'] == 1) {
                cookie('token', JwtAuth::getToken(['id' => $user['id']], sysValue('token_key')), 86400 * 365);
            }

            unset($user['password']);
            unset($user['status']);
            session(config('app.sess_user'), $user);

            $this->success(lang('login.success'));
        }
        $this->assign('captcha', $captcha);

        $username = cookie('username');
        $this->assign('username', $username);
        return $this->fetch();
    }

    /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        $userId = currentUserId();
        if (!empty($userId)) {
            Cache::delete('auth_code_' . $userId);
            Cache::delete('auth_init_' . $userId);
        }
        session(config('app.sess_user'), null);
        cookie('token', null);
        $this->success(lang('login.out_info'));
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return Captcha::create();
    }
}
